#!/usr/bin/env python3
"""
BoLe HR Platform - 系统启动脚本
一键启动前后端服务
"""

import os
import sys
import subprocess
import time
import signal
import threading
from pathlib import Path

class SystemManager:
    def __init__(self):
        self.backend_process = None
        self.frontend_process = None
        self.running = True
        
    def start_backend(self):
        """启动后端服务"""
        print("🚀 启动JH AI聊天服务...")
        print("⚠️ 注意：暂时使用独立的JH服务器（跳过lightrag功能）")
        try:
            # 在Windows上设置正确的编码环境
            env = os.environ.copy()
            if sys.platform == "win32":
                env['PYTHONIOENCODING'] = 'utf-8'
                env['PYTHONLEGACYWINDOWSSTDIO'] = '1'
            
            self.backend_process = subprocess.Popen([
                sys.executable, "simple_jh_server.py"
            ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, 
            encoding='utf-8', errors='replace', env=env)
            
            # 等待后端启动
            time.sleep(3)
            
            if self.backend_process.poll() is None:
                print("✅ JH AI聊天服务启动成功 - http://localhost:8000")
                return True
            else:
                stdout, stderr = self.backend_process.communicate()
                print(f"❌ 后端服务启动失败: {stderr}")
                return False
                
        except Exception as e:
            print(f"❌ 后端服务启动异常: {e}")
            return False
    
    def start_frontend(self):
        """启动前端服务"""
        print("🌐 启动前端Web服务...")
        try:
            frontend_dir = Path(__file__).parent / "frontend"
            
            self.frontend_process = subprocess.Popen([
                sys.executable, "server.py", "3000"
            ], cwd=frontend_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            encoding='utf-8', errors='ignore')
            
            # 等待前端启动
            time.sleep(2)
            
            if self.frontend_process.poll() is None:
                print("✅ 前端服务启动成功 - http://localhost:3000")
                return True
            else:
                stdout, stderr = self.frontend_process.communicate()
                print(f"❌ 前端服务启动失败: {stderr}")
                return False
                
        except Exception as e:
            print(f"❌ 前端服务启动异常: {e}")
            return False
    
    def stop_services(self):
        """停止所有服务"""
        print("\n🛑 正在停止服务...")
        
        if self.backend_process:
            self.backend_process.terminate()
            try:
                self.backend_process.wait(timeout=5)
                print("✅ 后端服务已停止")
            except subprocess.TimeoutExpired:
                self.backend_process.kill()
                print("⚠️ 强制停止后端服务")
        
        if self.frontend_process:
            self.frontend_process.terminate()
            try:
                self.frontend_process.wait(timeout=5)
                print("✅ 前端服务已停止")
            except subprocess.TimeoutExpired:
                self.frontend_process.kill()
                print("⚠️ 强制停止前端服务")
        
        self.running = False
    
    def monitor_processes(self):
        """监控进程状态"""
        while self.running:
            time.sleep(5)
            
            # 检查后端进程
            if self.backend_process and self.backend_process.poll() is not None:
                print("⚠️ 后端服务异常退出，尝试重启...")
                if not self.start_backend():
                    print("❌ 后端服务重启失败")
                    break
            
            # 检查前端进程
            if self.frontend_process and self.frontend_process.poll() is not None:
                print("⚠️ 前端服务异常退出，尝试重启...")
                if not self.start_frontend():
                    print("❌ 前端服务重启失败")
                    break
    
    def signal_handler(self, signum, frame):
        """信号处理"""
        print(f"\n📨 收到信号 {signum}，正在优雅退出...")
        self.stop_services()
        sys.exit(0)
    
    def run(self):
        """运行系统"""
        print("🎯 BoLe HR Platform - 智能招聘系统")
        print("=" * 60)
        
        # 注册信号处理
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        
        # 检查依赖
        if not self.check_dependencies():
            return False
        
        # 启动服务
        backend_ok = self.start_backend()
        if not backend_ok:
            print("❌ 无法启动后端服务，退出...")
            return False
        
        frontend_ok = self.start_frontend()
        if not frontend_ok:
            print("⚠️ 前端服务启动失败，但后端服务正常运行")
        
        print("\n" + "=" * 60)
        print("🎉 系统启动完成!")
        print("📖 使用指南:")
        print("  - 前端界面: http://localhost:3000")
        print("  - JH AI聊天服务: http://localhost:8000")
        print("  - JH AI聊天API: http://localhost:8000/docs")
        print("  - 健康检查: http://localhost:8000/health")
        print("  - JH数据分析: http://localhost:8000/frontend/jh_subsystem/jh_dashboard.html")
        print("\n👤 系统角色:")
        print("  - HR用户: 简历分析、候选人管理")
        print("  - 求职者: 职位搜索、数据分析")
        print("\n📊 JH子系统使用方法:")
        print("  1. 直接访问: http://localhost:8000/frontend/jh_subsystem/jh_dashboard.html")
        print("  2. 或通过前端界面选择'求职者'角色后点击'数据分析'")
        print("  3. 使用AI助手标签页进行智能对话")
        print("\n⌨️ 控制命令:")
        print("  - Ctrl+C: 停止服务")
        print("=" * 60)
        
        # 启动监控线程
        monitor_thread = threading.Thread(target=self.monitor_processes)
        monitor_thread.daemon = True
        monitor_thread.start()
        
        # 保持主线程运行
        try:
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            self.signal_handler(signal.SIGINT, None)
        
        return True
    
    def check_dependencies(self):
        """检查依赖"""
        print("🔍 检查系统依赖...")
        
        # 检查Python版本
        if sys.version_info < (3, 8):
            print("❌ Python版本需要3.8或更高")
            return False
        
        # 检查必要的包
        required_packages = ['fastapi', 'uvicorn', 'pydantic', 'sqlalchemy', 'pandas']
        missing_packages = []
        
        for package in required_packages:
            try:
                __import__(package)
            except ImportError:
                missing_packages.append(package)
        
        if missing_packages:
            print(f"❌ 缺少必要的包: {', '.join(missing_packages)}")
            print("请运行: pip install -r requirements.txt")
            return False
        
        # 检查前端文件
        frontend_files = [
            "frontend/index.html",
            "frontend/server.py",
            "frontend/styles/main.css",
            "frontend/jh_subsystem/jh_dashboard.html"
        ]
        
        missing_files = []
        for file_path in frontend_files:
            if not Path(file_path).exists():
                missing_files.append(file_path)
        
        if missing_files:
            print(f"❌ 缺少前端文件: {', '.join(missing_files)}")
            return False
        
        print("✅ 依赖检查通过")
        return True

def main():
    """主函数"""
    manager = SystemManager()
    
    try:
        success = manager.run()
        return 0 if success else 1
    except Exception as e:
        print(f"❌ 系统启动失败: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())